# Automatic network construction, module detection and module relating trains.

library(WGCNA)

args <- commandArgs(trailingOnly = TRUE)

exprFilePath = "/Users/zyl/Workspace/hzau/MOIN-Extension-Github/WGCNA-Extension/FemaleLiver-Data/datExpr.csv"
traitFilePath = "/Users/zyl/Workspace/hzau/MOIN-Extension-Github/WGCNA-Extension/FemaleLiver-Data/datTraits.csv"

datExpr = read.csv(exprFilePath, stringsAsFactors = FALSE, row.names = 1);
datTraits = read.csv(traitFilePath, stringsAsFactors = FALSE, row.names = 1);

nSamples = nrow(datExpr);
load("./network.RData")

# Recalculate MEs with color labels
moduleColors = labels2colors(net$colors)
MEs0 = moduleEigengenes(datExpr, moduleColors)$eigengenes
MEs = orderMEs(MEs0)
moduleTraitCor = cor(MEs, datTraits, use = "p");
moduleTraitPvalue = corPvalueStudent(moduleTraitCor, nSamples);
textMatrix = paste(signif(moduleTraitCor, 2), "\n(",
                   signif(moduleTraitPvalue, 1), ")", sep = "");

png(
  filename = "/Users/zyl/Workspace/hzau/MOIN-Extension-Github/WGCNA-Extension/FemaleLiver-Data/module_trait_heatmap.png",
  width = 13,
  height = 9,
  units = "in",
  res = 300
)
par(mar = c(6, 8.5, 3, 3));
labeledHeatmap(Matrix = moduleTraitCor,
               xLabels = names(datTraits),
               yLabels = names(MEs),
               ySymbols = names(MEs),
               colorLabels = FALSE,
               colors = blueWhiteRed(50),
               textMatrix = textMatrix,
               setStdMargins = FALSE,
               cex.text = 0.5,
               zlim = c(-1,1),
               main = paste("Module-trait relationships"))
dev.off()
